package com.example.jmx;

import com.example.jmx.mbean.UUIDService;

import javax.management.*;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.rmi.registry.LocateRegistry;

public class JMXClient {

    public static void start(int port, String host) throws MalformedObjectNameException, NotCompliantMBeanException, InstanceAlreadyExistsException, MBeanRegistrationException, IOException {
        System.out.println("JMX服务开始启动...");

        // 启动JMX服务并注册MBean
        MBeanServer server = ManagementFactory.getPlatformMBeanServer();
        ObjectName name = new ObjectName("geneUUIDMBean:name=geneUUID");
        server.registerMBean(new UUIDService(), name);
        System.out.println("MBean注册成功.");

        // 暴漏端口，提供服务
        LocateRegistry.createRegistry(port);
        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi");
        JMXConnectorServer connectorServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server);
        connectorServer.start();

        System.out.println("JMX服务启动成功.JConsole连接地址：" + host + ":" + port);
    }

}
